/*
 * @Author: lihaogn
 * @Date: 2023-02-07 00:01:08
 * @LastEditTime: 2023-02-12 20:54:17
 * @LastEditor: lihaogn
 * @Description:
 * @FilePath: \Lix-Luckyman\index.js
 */
const { createApp } = Vue;

const rootEle = document.documentElement;
const rootEleStyle = getComputedStyle(rootEle);
const wheelSize = rootEleStyle.getPropertyValue('--wheel-size');
const rootFontSize = rootEleStyle.fontSize;

/**
 * px转换成rem
 * @param {number} value px值
 * @param {boolean} needUnit 是否需要单位
 * @returns rem值
 */
const pxToRem = (value, needUnit) => {
  const res = value / parseInt(rootFontSize);
  return needUnit ? res + 'rem' : res;
};

/**
 * 获取随机数
 * @returns 随机数 [0, prizeList.length)
 */
function getRandomNum() {
  return Math.floor(Math.random() * prizeList.length);
}

const app = createApp({
  data() {
    return {
      mode: 0,
      activityTitle: activityTitle,
    };
  },

  methods: {
    /**
     * 切换抽奖模式
     * @param {number} value 抽奖模式代号
     */
    changeMode(value) {
      this.mode = value;
    },
  },
});

app.component('wheel-luck', {
  template: `
  <div class="wheel-lucky-container">
    <div v-for="index in prizeList.length" :key="index"
      :class="['light',{'light-blink-odd':isRunning&&index%2===1},{'light-blink-even':isRunning&&index%2===0}]"
      :style="{transform:\`translateX(-50%) rotate(\${(index - 1) * rotateAngle}deg)\`}"></div>

    <div class="wheel-panel" ref="wheelPanelRef" :style="[wheelPanelBackground, wheelPanelRotateStyle]">
      <div class="prize-item" v-for="(item,index) in prizeList" :key="index" :style="setPrizeItemStyle(index)">
        <span :style="prizeItemContentStyle">{{item.title}}</span>
      </div>
    </div>

    <div class="pointer" @click="start">start</div>
  </div>`,
  data() {
    return {
      // 转盘列表
      prizeList: [],
      isRunning: false, // 是否正在转动
      luckyId: 0, // 中奖的id
      basicRunAngles: 360 * 10, // 基本转动圈数
      wheelPanelRotateStyle: {},
      actuallyRunAngles: 0, // 实际应该转的度数
      isUnclock: false, // 是否逆时针旋转
    };
  },
  computed: {
    // 转动总角度
    runAngles() {
      let actual = this.luckyId * this.rotateAngle + this.rotateAngle / 2;
      this.actuallyRunAngles = actual;
      if (this.isUnclock) {
        // 逆时针转
        return -(this.basicRunAngles + actual);
      } else {
        // 顺时针转
        return this.basicRunAngles + 360 - actual;
      }
    },
    // 每个扇形的角度
    rotateAngle() {
      return 360 / this.prizeList.length;
    },
    // 每个扇形的样式
    wheelPanelBackground() {
      const len = this.prizeList.length;
      const colorList = ['#fff', 'rgb(252, 200, 0)'];
      let colorVal = '';
      for (let i = 0; i < len; i++) {
        colorVal += `${colorList[i % 2]} ${this.rotateAngle * i}deg ${this.rotateAngle * (i + 1)}deg,`;
      }

      return { background: `conic-gradient(${colorVal.slice(0, -1)})` };
    },
    // 奖项区域容器宽度
    prizeItemWidth() {
      return wheelSize * Math.sin(((this.rotateAngle / 2) * Math.PI) / 180);
    },
    // 每个奖项区域内容样式
    prizeItemContentStyle() {
      return { width: `${pxToRem(this.prizeItemWidth / 2, true)}` };
    },
  },
  created() {
    this.prizeList = [...prizeList];
    if (prizeList.length % 2 !== 0) {
      this.prizeList.push({ title: '再来一次' });
    }
  },
  beforeUnmount() {
    this.$refs['wheelPanelRef'].removeEventListener('transitionend', this.stop);
  },
  methods: {
    /**
     * 停止转动
     */
    stop() {
      this.isRunning = false;
      if (this.isUnclock) {
        // 逆时针转
        this.wheelPanelRotateStyle = {
          transform: `rotate(${-this.actuallyRunAngles}deg)`, // 计算后简写
        };
      } else {
        // 顺时针转
        this.wheelPanelRotateStyle = { transform: `rotate(${360 - this.actuallyRunAngles}deg)` };
      }
    },
    /**
     * 转动
     */
    startRotate() {
      this.wheelPanelRotateStyle = { transform: `rotate(${this.runAngles}deg)`, transition: `transform 4s ease` };
      this.$refs['wheelPanelRef'].addEventListener('transitionend', this.stop);
    },
    /**
     * 开始抽奖
     */
    start() {
      if (!this.isRunning) {
        this.isRunning = true;
        this.luckyId = getRandomNum();
        console.log('wheel-lucky-man', this.luckyId);
        this.startRotate();
      }
    },
    /**
     * 计算每个扇形的样式
     * @param {number} index 扇形索引
     * @returns 每个扇形的样式
     */
    setPrizeItemStyle(index) {
      return `width: ${pxToRem(this.prizeItemWidth, true)}px; 
      height: ${pxToRem(wheelSize / 2, true)}; 
      transform: rotate(${this.rotateAngle * index + this.rotateAngle / 2}deg); 
      transform-origin: 50% 100%;`;
    },
  },
});

app.component('text-luck', {
  template: `
    <div class="text-luck-comp">
      <span class="text-luck-content">{{rollValue}}</span><br />
      <button @click="begin">开始</button>
    </div>
  `,
  data() {
    return {
      rollValue: '',
      start: 0,
      end: prizeList.length - 1,
      startTime: null,
      duration: 1000, // 持续时间 ms
      isRunning: false,
      luckyman: '',
    };
  },
  created() {
    this.rollValue = prizeList[0].title;
    this.end = (this.duration / 20) * prizeList.length - 1;
  },
  methods: {
    /**
     * 开始事件
     * @returns
     */
    begin() {
      if (this.isRunning) {
        return;
      }
      this.isRunning = true;
      this.startTime = null;
      this.luckyman = getRandomNum();
      console.log('roll-lucky-man', this.luckyman);
      requestAnimationFrame(this.roll);
    },
    /**
     * 值滚动
     * @param {number} timestamp 时间戳
     */
    roll(timestamp) {
      if (!this.startTime) {
        this.startTime = timestamp;
      }
      const progress = timestamp - this.startTime;
      const index = parseInt(this.start + (this.end - this.start) * (progress / this.duration));
      if (index < this.end) {
        this.rollValue = prizeList[index % prizeList.length].title;
        window.requestAnimationFrame(this.roll);
      } else {
        this.rollValue = prizeList[this.luckyman].title;
        this.isRunning = false;
      }
    },
  },
});

app.component('nine-block-luck', {
  template: `
  <div class="nine-block-luck-comp">
    <div class="container" >
      <div :class="['grid-item',{'active':currentIndex===index}]" v-for="(item,index) in prizeList" :key="index">
        <span v-if="index!==4">{{item.title}}</span>
        <div v-else @click="begin">{{item.title}}</div>
      </div>
    </div>
  </div>
`,
  data() {
    return {
      prizeList: [...prizeList.slice(0, 8)],
      prizeSort: [0, 1, 2, 5, 8, 7, 6, 3],
      isRunning: false,
      luckyId: 0,
      timerIns: null,
      currentIndex: -1, // 当前索引
      runSteps: 0, // 已跑步数
      speed: 100, // 跑的速度（延时）
    };
  },
  computed: {
    // 总共要跑的步数
    totalSteps() {
      return 32 + this.prizeSort.indexOf(this.luckyId);
    },
  },
  created() {
    this.prizeList.splice(4, 0, { title: '开始' });
  },
  methods: {
    /**
     * 动画执行
     * @returns
     */
    run() {
      if (this.runSteps > this.totalSteps) {
        // 结束
        this.timerIns && clearTimeout(this.timerIns);
        this.isRunning = false;
        this.runSteps = 0;
        this.speed = 100;
        return;
      }

      this.currentIndex = this.prizeSort[this.runSteps % 8];
      this.runSteps++;
      if (this.runSteps >= 24) {
        this.speed = 300;
      }

      this.timerIns = setTimeout(() => {
        this.run();
      }, this.speed);
    },
    /**
     * 开始事件
     * @returns
     */
    begin() {
      if (this.isRunning) {
        return;
      }
      this.isRunning = true;
      this.luckyId = this.getLuckyMan();
      console.log('nine-block-lucky-man', this.luckyId);
      this.currentIndex = 0;
      this.run();
    },
    /**
     * 获取中奖索引值
     * @returns {number} 奖品索引
     */
    getLuckyMan() {
      return this.prizeSort[Math.floor(Math.random() * this.prizeSort.length)];
    },
  },
});

app.mount('#app');
